package com.song.gateway.filters;

import com.song.common.model.WhiteList;
import com.song.common.util.JwtUtil;
import com.song.gateway.util.WhiteListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局过滤器
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private WhiteListUtil whiteListUtil;

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //如果是白名单，放行
        if (whiteListUtil.isWhiteList(path)){
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("Authorization");
        boolean verify = JwtUtil.verify(token, JwtUtil.getUsername(token));
        if (!verify){
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 值越小，优先级越高
     * @return
     */
    public int getOrder() {
        return 0;
    }
}
